package com.xcm.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.xcm.cache.RedisCacheDao;
import com.xcm.config.CustomProperties;
import com.xcm.constant.*;
import com.xcm.exception.ControllerException;
import com.xcm.exception.ServiceException;
import com.xcm.model.JsonResponse;
import com.xcm.model.TbDeviceInfo;
import com.xcm.model.dto.DeviceInfoListDTO;
import com.xcm.model.vo.DeviceLogListVO;
import com.xcm.page.PageInfo;
import com.xcm.service.DeviceInfoService;
import com.xcm.service.DeviceLogService;
import com.xcm.util.DateUtils;
import com.xcm.util.GetUserUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/deviceInfo")
public class DeviceInfoController {

	private static Logger logger = LoggerFactory.getLogger(DeviceInfoController.class);
	@Autowired
	private DeviceInfoService deviceInfoService;
	@Autowired
	private RedisCacheDao redisCacheDao;
	@Autowired
	private DeviceLogService deviceLogService;
	@Autowired
	private CustomProperties customProperties;

	/**
	 * 终端分页列表
	 */
	@RequestMapping(value = "/listByPage")
	public String listByPage(String groupCode, String deviceNum, String deviceIp, String deviceMac, Integer deviceStatus, Integer pageNum, Integer pageSize, Model model) {
		if ((StringUtils.isNotBlank(groupCode) && groupCode.length() > 32) || (StringUtils.isNotBlank(deviceNum) && deviceNum.length() > 50)
				|| (StringUtils.isNotBlank(deviceIp) && deviceIp.length() > 32) || (StringUtils.isNotBlank(deviceMac) && deviceMac.length() > 32)
				|| (deviceStatus != null && (deviceStatus < 0 || deviceStatus > 1))) {
			model.addAttribute(ClientConstant.MSG_PARAM_SIZE_ERROR);
			return "";
		}
		//设置默认值
		if (pageNum == null) {
			pageNum = PageConstant.DEFAULT_PAGE_NUM;
		}
		if (pageSize == null) {
			pageSize = PageConstant.DEFAULT_PAGE_SIZE;
		}
		if(StringUtils.isNotBlank(groupCode) && BusinessConstant.GROUP_CODE_ALL_DEVICE.equals(groupCode)) {
			groupCode = null;
		}
		Page<DeviceInfoListDTO> page = deviceInfoService.listByPage(groupCode, deviceNum, deviceIp, deviceMac, deviceStatus, pageNum, pageSize);

		// 统计离线终端数量
		Long deviceOfflineCount = 0L;
		//统计在线终端数量
		Long deviceOnlineCount = 0L;
		if(deviceStatus == null && StringUtils.isBlank(deviceNum) && StringUtils.isBlank(deviceIp) && StringUtils.isBlank(deviceMac) && StringUtils.isBlank(groupCode)) {
			// 查询条件为空时，统计所有数量
			deviceOfflineCount = deviceInfoService.getOfflineDeviceInfoCount();
			deviceOnlineCount = deviceInfoService.getOnlineDeviceInfoCount();
		}else if (deviceStatus != null && BusinessConstant.DEVICE_INFO_STATUS_ON_LINE == deviceStatus) {
			// 查询条件:在线状态“在线”
			deviceOnlineCount = page.getTotal();
		}else if(deviceStatus != null && BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE == deviceStatus) {
			// 查询条件：在线状态"离线”
			deviceOfflineCount = page.getTotal();
		}else if(StringUtils.isNotBlank(deviceNum)) {
			// 查询条件：机器编码
			deviceOnlineCount = deviceInfoService.getOnlineDeviceInfoCountbyDeviceNum(deviceNum);
			deviceOfflineCount = deviceInfoService.getOfflineDeviceInfoCountbyDeviceNum(deviceNum);
		}else if(StringUtils.isNotBlank(deviceIp)) {
			// 查询条件：IP地址
			deviceOnlineCount = deviceInfoService.getOnlineDeviceInfoCountbyDeviceIp(deviceIp);
			deviceOfflineCount = deviceInfoService.getOfflineDeviceInfoCountbyDeviceIp(deviceIp);
		}else if(StringUtils.isNotBlank(deviceMac)) {
			// 查询条件：mac地址
			deviceOnlineCount = deviceInfoService.getOnlineDeviceInfoCountbyDeviceMac(deviceMac);
			deviceOfflineCount = deviceInfoService.getOfflineDeviceInfoCountbyDeviceMac(deviceMac);
		}else if(StringUtils.isNotBlank(groupCode)) {
			// 查询条件：分组编码
			deviceOnlineCount = deviceInfoService.getOnlineDeviceInfoCountbyGroupCode(groupCode);
			deviceOfflineCount = deviceInfoService.getOfflineDeviceInfoCountbyGroupCode(groupCode);
		}

		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("result", page.getResult());
		model.addAttribute("total", page.getTotal());
		model.addAttribute("resultList", page.getResult());
		//查询条件回显
		// 分组编号
		model.addAttribute("groupCodeReview",groupCode);
		// 终端机器码
		model.addAttribute("deviceNumReview",deviceNum);
		// 终端Ip
		model.addAttribute("deviceIpReview",deviceIp);
		// 终端mac
		model.addAttribute("deviceMacReview",deviceMac);
		// 终端状态
		model.addAttribute("deviceStatusReview",deviceStatus);
		//离线终端数量
		model.addAttribute("deviceOfflineCount",deviceOfflineCount);
		// 在线终端数量
		model.addAttribute("deviceOnlineCount",deviceOnlineCount);
		return "deviceInfo_list";
	}

	/**
	 * 修改机器码
	 */
	@ResponseBody
	@RequestMapping(value = "/updateDeviceNum")
	public Object updateDeviceNum(Long deviceInfoId, String deviceNum, HttpServletRequest request) {
		//获取用户信息
		JSONObject user = null;
		try {
			user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("DeviceInfoController updateDeviceNum 修改机器码失败：" + e.getMessage());
			return new ControllerException(e.getMessage());
		}
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		//验证终端ID
		if (deviceInfoId == null) {
			return new ControllerException("终端ID不能为空");
		}
		//验证机器码
		if (StringUtils.isBlank(deviceNum)) {
			return new ControllerException("机器码不能为空");
		}
		TbDeviceInfo tbDeviceInfo = deviceInfoService.getDeviceInfoById(deviceInfoId);
		if(tbDeviceInfo == null) {
			return new ControllerException("该终端设备不存在，请刷新后重试");
		}
		try {
			String deviceMac = tbDeviceInfo.getDeviceMac();
			deviceInfoService.updateDeviceNum(deviceInfoId, deviceNum, deviceMac, user, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceInfoController updateDeviceNum 修改机器码失败：" + e.getMessage());
			return new ControllerException("修改机器码失败");
		}
		return "";
	}

	/**
	 * 关机
	 */
	@ResponseBody
	@RequestMapping(value = "/shutdown")
	public Object shutdown(String deviceMacs, String groupCode, HttpServletRequest request) {
		//获取用户信息
		JSONObject user = null;
		try {
			user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("DeviceInfoController shutdown 关机失败：" + e.getMessage());
			return new ControllerException(e.getMessage());
		}
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		//	deviceMacs和groupCode不能同时为空
		if (StringUtils.isBlank(deviceMacs) && StringUtils.isBlank(groupCode)) {
			return new ControllerException(ClientConstant.MSG_PARAM_ERROR);
		}
		//验证分组码长度
		if (groupCode.length() > 32) {
			return new ControllerException(ClientConstant.MSG_PARAM_SIZE_ERROR);
		}
		try {
			deviceInfoService.shutdown(deviceMacs, groupCode, user, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceInfoController shutdown 关机失败：" + e.getMessage());
			return new ControllerException("关机失败");
		}
		return "";
	}

	/**
	 * 重启
	 */
	@ResponseBody
	@RequestMapping(value = "/restart")
	public Object restart(String deviceMacs, String groupCode, HttpServletRequest request) {
		//获取用户信息
		JSONObject user = null;
		try {
			user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("DeviceInfoController restart 重启失败：" + e.getMessage());
			return new ControllerException(e.getMessage());
		}
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		//	deviceMacs和groupCode不能同时为空
		if (StringUtils.isBlank(deviceMacs) && StringUtils.isBlank(groupCode)) {
			return new ControllerException(ClientConstant.MSG_PARAM_ERROR);
		}
		//验证分组码长度
		if (groupCode.length() > 32) {
			return new ControllerException(ClientConstant.MSG_PARAM_SIZE_ERROR);
		}
		try {
			deviceInfoService.restart(deviceMacs, groupCode, user, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceInfoController restart 重启失败：" + e.getMessage());
			return new ControllerException("重启失败");
		}
		return "";
	}

	/**
	 * 指定终端升级
	 */
	@ResponseBody
	@RequestMapping(value = "/setDeviceUpdate")
	public Object setDeviceUpdate(Long deviceInfoId, Long deviceUpgradeId, HttpServletRequest request) {
		//获取用户信息
		JSONObject user = null;
		try {
			user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("DeviceInfoController setDeviceUpdate 指定终端升级失败：" + e.getMessage());
			return new ControllerException(e.getMessage());
		}
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if (deviceInfoId == null || deviceUpgradeId == null) {
			return new ControllerException("参数不能为空");
		}
		try {
			deviceInfoService.updateDeviceUpdate(deviceInfoId, deviceUpgradeId, user, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceInfoController setDeviceUpdate 指定终端升级失败：" + e.getMessage());
			return new ControllerException("指定终端升级失败");
		}
		return "";
	}

	/**
	 * 设置定时开关机
	 */
	@ResponseBody
	@RequestMapping(value = "/setTimerShutDownOrStart")
	public Object setTimerShutDownOrStart(String deviceMacs, String groupCode, Integer useTimer, String bootTime, String offTime, HttpServletRequest request) {
		//获取用户信息
		JSONObject user = null;
		try {
			user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("DeviceInfoController setTimerShutDownOrStart 设置定时开关机失败：" + e.getMessage());
			return new ControllerException(e.getMessage());
		}
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if ((StringUtils.isBlank(deviceMacs) && StringUtils.isBlank(groupCode)) || useTimer == null || StringUtils.isBlank(bootTime) || StringUtils.isBlank(offTime)) {
			return new ControllerException("输入参数不能为空");
		}
		try {
			// 把字符串日期转换为LonG类型日期
			Long longBootTime = DateUtils.stringTimeToLongTimeStamp(bootTime, DateFormatConstant.DATE_ONLYHM_24);
			Long longOffTime = DateUtils.stringTimeToLongTimeStamp(offTime,DateFormatConstant.DATE_ONLYHM_24);
			deviceInfoService.updateDeviceBootOffTime(deviceMacs, groupCode, useTimer, longBootTime, longOffTime, user, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceInfoController setTimerShutDownOrStart 设置定时开关机失败：" + e.getMessage());
			return new ControllerException("设置定时开关机失败");
		}
		return "";
	}

	/**
	 * 设置音量
	 */
	@ResponseBody
	@RequestMapping(value = "/setVolume")
	public Object setVolume(String deviceMacs, String groupCode, Integer deviceVolume, HttpServletRequest request) {
		//获取用户信息
		JSONObject user = null;
		try {
			user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("DeviceInfoController setVolume 设置音量失败：" + e.getMessage());
			return new ControllerException(e.getMessage());
		}
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if ((StringUtils.isBlank(deviceMacs) && StringUtils.isBlank(groupCode)) || deviceVolume == null) {
			return new ControllerException("输入参数不能为空");
		}
		try {
			deviceInfoService.updateDeviceVolume(deviceMacs, groupCode, deviceVolume, user, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceInfoController setVolume 设置音量失败：" + e.getMessage());
			return new ControllerException("设置音量失败");
		}
		return "";
	}

	/**
	 * 上传(终端)日志
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadLog")
	public Object uploadLog(String mac, HttpServletRequest request) {
		//获取用户信息
		JSONObject user = null;
		try {
			user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("DeviceInfoController uploadLog 上传日志失败：" + e.getMessage());
			return new ControllerException(e.getMessage());
		}
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if (StringUtils.isBlank(mac)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		try {
			deviceInfoService.uploadLog(mac, user, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceInfoController uploadLog 上传日志失败：" + e.getMessage());
			return new ControllerException("上传日志失败");
		}
		return "";
	}

	/**
	 * 跳转到终端日志列表页面
	 * @return
	 */
	@RequestMapping(value = "/deviceLogList")
	public Object deviceLogList(String deviceMac, Model model){
		model.addAttribute("deviceMac",deviceMac);
		return "deviceLog_list";
	}


	/**
	 * 获取(终端)日志
	 */
	@ResponseBody
	@RequestMapping(value = "/getLogs")
	public Object getLogs(Integer pageNum, Integer pageSize, String mac, Model modelView) {
		if (StringUtils.isBlank(mac)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		try {
            if (pageNum == null) {
                pageNum = PageConstant.DEFAULT_PAGE_NUM;
            }
            if (pageSize == null) {
                pageSize = PageConstant.DEFAULT_PAGE_SIZE;
            }
            PageInfo<DeviceLogListVO> pageInfo = deviceLogService.listDeviceLogsByPage(mac,pageNum,pageSize);
            modelView.addAttribute("logList", pageInfo.getList());
            modelView.addAttribute("total", pageInfo.getTotal());
            modelView.addAttribute("pageNum", pageNum);
            modelView.addAttribute("pageSize", pageSize);
            return modelView;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceInfoController getLogs 获取日志失败：" + e.getMessage());
			return new ControllerException("获取日志失败");
		}
	}

	/**
	 * 删除(终端)日志
	 *
	 * @param deviceLogId 终端日志id
	 */
	@ResponseBody
	@RequestMapping(value = "deleteLog")
	public Object deleteLog(Long deviceLogId) {
		if (deviceLogId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		try {
			deviceLogService.deleteLogById(deviceLogId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceInfoController getLogs 获取日志失败：" + e.getMessage());
			return new ControllerException("获取日志失败");
		}
		return "";
	}

	/**
	 * ajax查询终端设备详情页
	 * @return
	 */
	@RequestMapping(value = "/getDeviceInfoDetailAjax")
	@ResponseBody
	public Object getDeviceInfoDetailAjax(String deviceInfoId) {
		if (StringUtils.isBlank(deviceInfoId)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		TbDeviceInfo TbDeviceInfo = deviceInfoService.getDeviceInfoById(Long.valueOf(deviceInfoId));
		if(TbDeviceInfo == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "该终端设备不存在，请重试");
		}
		// 开关机时间处理
		if("".equals(TbDeviceInfo.getBootTime())) {
			TbDeviceInfo.setBootTime("暂无");
		}else {
			Long longBootTime = Long.valueOf(TbDeviceInfo.getBootTime());
			String stringBootTime = DateUtils.longTimeStampToStringDate(longBootTime,DateFormatConstant.DATE_ONLYHM_24);
			TbDeviceInfo.setBootTime(stringBootTime);
		}
		if("".equals(TbDeviceInfo.getOffTime())) {
			TbDeviceInfo.setOffTime("暂无");
		}else {
			Long longOffTime = Long.valueOf(TbDeviceInfo.getOffTime());
			String stringOffTime = DateUtils.longTimeStampToStringDate(longOffTime,DateFormatConstant.DATE_ONLYHM_24);
			TbDeviceInfo.setOffTime(stringOffTime);
		}
		return new JsonResponse(ResponseConstant.CODE_SUCCESS, TbDeviceInfo, "查询成功");
	}

}
